import React, { Component } from "react";

import {
  TouchableOpacity,
  View,
  Text,
  Image,
  DeviceEventEmitter
} from "react-native";

import { NOTICE } from "../../../config/Api";
import http from "../../../util/http";
import { NewSliderContainer } from "../../../style/index";

export default class noticeList extends Component {
  state = {
    data: [],
    index: 0
  };

  async getNoticelist() {
    const data = await http.get(NOTICE);
    this.setState({
      data: data.data.list.slice(0, 3)
    });
  }

  runNews() {
    let index = this.state.index;
    setInterval(() => {
      this.setState({
        index: index + 1 === this.state.data.length ? 0 : ++index
      });
    }, 3000);
  }

  componentDidMount() {
    this.runNews();
  }

  refresh() {
    this.getNoticelist();
  }

  componentWillMount() {
    this.refresh();
    this.subscription = DeviceEventEmitter.addListener("refresh", () => {
      this.refresh();
    });
  }

  componentWillUnmount() {
    this.subscription.remove();
  }

  render() {
    return (
      <View style={NewSliderContainer.newSlider}>
        <View style={NewSliderContainer.left}>
          <Image
            style={{ resizeMode: "contain", width: 22, height: 22 }}
            source={require("../../../assets/voice-icon.png")}
          />
        </View>
        <View style={NewSliderContainer.list}>
          {this.state.data.map(
            (notice, index) =>
              index == this.state.index ? (
                <TouchableOpacity
                  style={NewSliderContainer.list}
                  key={index}
                  onPress={() => this.props.navigation.navigate("NoticeList")}
                >
                  <Text
                    style={[
                      NewSliderContainer.list,
                      { color: "#fff", lineHeight: 40 }
                    ]}
                  >
                    {notice.title}
                  </Text>
                </TouchableOpacity>
              ) : null
          )}
        </View>
        <View style={NewSliderContainer.left}>
          <Text style={{ color: "#fff", fontSize: 14 }}>></Text>
        </View>
      </View>
    );
  }
}
